package edu.geo.db.conn;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Wrapper para gestión de conexiones a la base de datos.
 * 
 * @author alejandro.sanchez
 *
 */
public class DBConnection extends DBConnectionProvider{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 5373895078967199507L;

	static private final Log LOGGER = LogFactory.getLog(DBConnection.class);
	
	private String dbResource;
	
	
	public DBConnection(String dbName)
	{
		dbResource = dbName;
	}

	public Connection getConnection() throws SQLException{
		Connection conn = null;
		try
		{
			Context context = new InitialContext();
			DataSource ds = (DataSource) context.lookup( "java:comp/env/jdbc/" + dbResource );
			conn = ds.getConnection();			
		}
		catch (NamingException e)
		{
			LOGGER.error(e.getMessage(), e);
			throw new SQLException("Cannot open the db connection: " + e.getExplanation());
		}
		catch ( Exception e )
		{
			LOGGER.error(e.getMessage(), e);			
		}
		return conn;
	}
}
